import {
    AfterViewInit,
    ChangeDetectionStrategy,
    Component,
    ElementRef,
    EventEmitter,
    Input,
    OnChanges,
    OnDestroy,
    OnInit,
    Output,
    Renderer2,
    SimpleChanges,
    ViewChild
} from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ConfigModule } from 'src/app/config.module';
import { ActivatedRoute, Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Store } from '@ngxs/store';
import { DragDrop } from '@angular/cdk/drag-drop';
import { NgxPermissionsService } from 'ngx-permissions';
import { NzFormatEmitEvent, NzTreeNode } from 'ng-zorro-antd/tree';
import { NzContextMenuService, NzDropdownMenuComponent } from 'ng-zorro-antd/dropdown';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CategoryTreeNodeModel } from '../../../models/category/category.model';
import { TreeUtil } from '../tree-util';

@Component({
    selector: 'app-edit-tree',
    changeDetection:  ChangeDetectionStrategy.Default,
    templateUrl: './edit-tree.component.html',
    styleUrls: ['./edit-tree.component.scss']
})
export class EditTreeComponent implements OnInit, AfterViewInit, OnDestroy, OnChanges {

    @ViewChild('modalContent') modalContent;
    @ViewChild('modalFooter') modalFooter;
    @ViewChild('titleInput') titleInput: ElementRef;
    @ViewChild('treeOne') treeOne;

    @Input()
    treeData: NzTreeNode[] = []; //菜单树的数据
    @Output()
    treeDataChange = new EventEmitter<any>();
    @Input()
    treeDataChangeRandom: number; //菜单树的数据

    @Output()
    searchFunction = new EventEmitter<any>();
    @Output()
    addFunction = new EventEmitter<any>();
    @Output()
    editFunction = new EventEmitter<any>();
    @Output()
    deleteFunction = new EventEmitter<any>();
    @Output()
    openFunction = new EventEmitter<any>();
    @Input()
    selectKey: string[];

    searchValue: string;
    activatedNode?: NzTreeNode;
    @Input()
    model = false;
    @Input()
    private expandMap: any;
    @Output()
    expandMapChange = new EventEmitter<any>();
    constructor(
        public _config: ConfigModule,
        private _formBuilder: FormBuilder,
        private _router: Router,
        private _nzModalService: NzModalService,
        private _activatedRoute: ActivatedRoute,
        private _renderer2: Renderer2,
        private _dragDrop: DragDrop,
        private _store: Store,
        private _ngxPermissionsService: NgxPermissionsService,
        private nzContextMenuService: NzContextMenuService,
        private message: NzMessageService
    ) {
    }

    ngOnChanges(changes: SimpleChanges): void {
        if (changes.hasOwnProperty('treeData') || changes.hasOwnProperty('treeDataChangeRandom')){
            if (this.treeData){
                this.treeData = [...this.treeData];
            }
        }
    }

    treeDataChange1(){
        if (this.treeData){
            this.treeData = [...this.treeData];
        }
    }

    ngOnInit() {
    }

    ngAfterViewInit() {
    }
    ngOnDestroy() {
    }

    delete(node: NzTreeNode): void {
        this.deleteFunction.emit(node);
    }

    editStatusChange(node: any): void {
        node.edit = !node.edit;
        this.elementFocus();
    }

    elementFocus(){
        setTimeout(() => {
            this.titleInput.nativeElement.focus()
        },500)
    }
    elementBlur(node: any){
        this.editFunction.emit(node);
    }

    search(e){
        if (e.code === 'Enter'){
            this.searchFunction.emit(this.searchValue);
        }
    }
    refresh(){
        this.searchFunction.emit();
    }

    open(data: any): void {
        let changeTreePositionData = TreeUtil.changeTreePositionSelected(this.treeData,data.node.origin.key);
        this.treeData = [...changeTreePositionData]
        this.openFunction.emit(data.node.key);
    }

    add(node:any){
        if (node == null){
            let a = {title:'新建分类',key:'',id:'',isLeaf: null, parentId:'',edit:true,selected:true,children:[]} as CategoryTreeNodeModel
            this.treeData.push(a);
            this.treeData = [...this.treeData];
        }else {
            let a = {title:'新建分类',key:'',id:'',isLeaf: null, parentId:node.key,edit:true,selected:true,children:[]} as CategoryTreeNodeModel
            node.expanded = true;
            this.changeExpand();
            node.children.push(a);
            this.treeData = TreeUtil.changeTreePositionData(this.treeData,node.key,node);
            this.treeData = [...this.treeData];
        }
        this.elementFocus();
    }

    activeNode(data: NzFormatEmitEvent): void {
        this.activatedNode = data.node!;
    }

    nzEvent(event: NzFormatEmitEvent): void {
    }

    currentNode: NzTreeNode;

    /**
     * 右键菜单
     */
     contextMenu($event: MouseEvent, menu: NzDropdownMenuComponent,node: NzTreeNode): void {
        this.currentNode=node;
        this.nzContextMenuService.create($event, menu);
    }

    completeEdit($event: KeyboardEvent, node: any) {
        if ($event.code === 'Enter') {
            this.editFunction.emit(node);
        }
    }

    changeExpand() {
        this.expandMap = TreeUtil.initExpandMap(this.treeData, this.expandMap);
    }

    protected readonly JSON = JSON;
    protected readonly String = String;

    dragEnd(event: any) {
        let node = event.node;
        node.parentId = event.node.getParentNode()==null ? '0' : event.node.getParentNode().key;
        this.editFunction.emit(node);
    }

    reSelect(){
        let changeTreePositionData = TreeUtil.changeTreePositionSelected(this.treeData,this.selectKey[0]);
        this.treeData = [...changeTreePositionData]
    }

}
